import requestClass from "./requestClass";
import baseUrl from "@/config";
import qs from "qs";

const Request = new requestClass();

// 请求拦截器
Request.interceptors.request((request: any) => {
  if (uni.getStorageSync("access_token")) {
	request.header["auth-token"] = uni.getStorageSync("access_token");
	request.header["userId"] = uni.getStorageSync("userId");
  }
  if (request.header.contentType) {
    request.header["content-type"] = request.header.contentType;
    // request.header["Auth-Token"] =
    //   "eyJhbGciOiJIUzUxMiJ9.eyJleHAiOjE2OTU4Njg4MDIsInN1YiI6ImFkbWluIiwiY3JlYXRlZCI6MTY5NTYwOTYwMjY0Mn0._jWQd1KFsOKhNAnMVOBoWmkwmdTtPq0D7Yx336z6L1bfcyZAVF85i8csbDirebf_-rRdj7s4ymL5EiFPbWd3Pw";
    delete request.header.contentType;
  }
  if (request.method === "GET") {
    request.data = qs.stringify(request.data);
	if(request.data){
		request.url = request.url + "?" + request.data;
	}else{
		request.url = request.url;
	}
  }

  //判断是微信还是支付宝，0：支付宝 1：微信
  const type = uni.getSystemInfoSync().uniPlatform;
  request.data = {
    ...request.data,
    // appId: uni.getAccountInfoSync().miniProgram.appId,
    // appType: type == "mp-alipay" ? 0 : 1,
    // openId: uni.getStorageSync("openId"),
    // openId: "041C1A78HlgIMCHJ0QF0hrHvcy4JVx0rVtUsk1LesCUCWMf",
  };
  return request;
});

// 响应拦截器
Request.interceptors.response((response: any) => {
  if (response.code != 200 && response.code != 401) {
    uni.showToast({ title: response.msg });
  }

  // 还未授权
  if (response.code == 401) {
    uni.showModal({
      title: "提示",
      content: "功能将被受限，点击按钮授权 ",
      showCancel: true,
      confirmText: "授权",
      success: ({ confirm, cancel }) => {
        if (confirm) {
          uni.navigateTo({
            url: "/pages/auth/index",
          });
        }
        if (cancel) {
          uni.navigateBack({ delta: 1 });
        }
      },
    });
  }

  const token = uni.getStorageSync("token");
  // if (response.data.code === 403) {
  //   uni.showToast({
  //     title: token ? '请重新登录' : '请先登录',
  //     icon: 'none',
  //     duration: 2000,
  //   })
  //   uni.removeStorageSync('token')
  //   uni.removeStorageSync('userInfo')
  // }
  return response;
});

// 设置默认配置
Request.setConfig((config: any) => {
  config.baseURL = baseUrl;
  // config.baseURL = "http://192.168.31.26:8060/api";
  if (uni.getStorageSync("token")) {
    config.header["Authorization"] = "Bearer " + uni.getStorageSync("token");
  }
  return config;
});

export default Request;
